#!/bin/bash

function error()
{
    echo "postupgrade error!" "$1" 
    exit
}

#
# The shell app allows the user to select the original application that will be
# updated. It then writes the name of the original app and the path of the
# app into two separate files.
#

AppName="`cat /tmp/MacSoftInstaller/_AppName.txt`"
AppPath="`cat /tmp/MacSoftInstaller/_AppPath.txt`"

echo Selected app to be updated: $AppPath$AppName

#
# On 10.3.9, the Installer doesn't seem to join resource and data forks back
# together until after the scripts are run. Thus, any resource files that we
# ditto in this script will be bad. So before doing anything, we look for all
# resource files and join them back together.
#

find "/tmp/MacSoftInstaller" -type d | while read dir ; do
	/System/Library/CoreServices/FixupResourceForks "$dir"
done

#
# Update the original application with any new files we included
#

#
# AppName is the file we want to update. However, this may not be the application's
# original name from when it was first Installed. The user may have changed the
# name of the app in the Finder (ie, "Halo.app" to "Halo Universal.app").
# To protect us from copy errors arising from file names being out of sync, the
# shell app also writes out the name of the app stored in the Package.
#

AppInPackage="`cat /tmp/MacSoftInstaller/_AppInPackage.txt`"

#
# Calculate the length of the path so we can use it to truncate the filename
#

temp="/tmp/MacSoftInstaller/$AppInPackage"
len=${#temp}

#
# Do the actual copy. Copy only if the file is newer (-nt)
# Form is: [ "$newfile" -nt "$oldfile" ] && cp -- "$newfile" "$oldfile"
# Note1: Use ditto to preserve Mac creation and mod times
# Note2: ':len' means to drop the first 'len' characters of the path (leaving just the filename)
# Note3: Took out -nt due to problems with 10.3.9 setting mod dates incorrectly when joining forks
#

find "/tmp/MacSoftInstaller/$AppInPackage" -type f | while read file ; do
#	[ "$file" -nt "$AppPath$AppName/${file:len}" ] && ditto -V --rsrc "$file" "$AppPath$AppName/${file:len}" 
	ditto -V --rsrc "$file" "$AppPath$AppName/${file:len}" 
done

#
# Touch the app so the Finder will show the updated version number
#

touch "$AppPath$AppName"

#
# Clean up the /tmp folder
#

rm -r "/tmp/MacSoftInstaller"/*

exit 0
